<template>
  <div>
    <!-- 添加按钮 -->
    <el-button icon="el-icon-plus" type="success" @click="open('add')"
    style="float:right;margin-bottom:5px;">添加</el-button>

    <!-- 列表展示 -->
    <el-table style="width: 100%" :data="list" v-loading="loading"  
      element-loading-text="拼命加载中"
      element-loading-spinner="el-icon-loading">
      <el-table-column label="图片" prop="image_src">
        <template v-slot="props">
          <img :src="props.row.image_src" width="100"/>
        </template>
      </el-table-column>
      <el-table-column label="链接" prop="navigator_url"></el-table-column>
      <el-table-column label="打开方式" prop="open_type"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="props">
          <el-button type="warning" @click="open('update',props.row)">修改</el-button>
          <el-button type="danger" @click="del(props.row._id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/修改 弹框 -->
    <el-dialog :title="openType=='add'?'添加轮播图':'修改轮播图'" @close="closeDialog" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="myform">
        <el-form-item label="商品编号" prop="goods_id" :label-width="formLabelWidth">
          <el-input v-model="form.goods_id" autocomplete="off" style="width:300px;"></el-input>
        </el-form-item>
        <el-form-item label="轮播图" prop="image_src" :label-width="formLabelWidth">
          <!-- <el-input v-model="form.image_src" autocomplete="off" style="width:300px;"></el-input>
           -->
          <el-upload style="width:300px;"
            class="upload-demo"
            action=""
            :before-upload="uploadPhoto"
            :auto-upload="true"
            :file-list="fileList"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="页面链接" :label-width="formLabelWidth" prop="navigator_url">
          <el-input v-model="form.navigator_url" autocomplete="off"  style="width:300px;"></el-input>
        </el-form-item>
        <el-form-item label="跳转方式" :label-width="formLabelWidth" prop="open_type">
          <el-select v-model="form.open_type" placeholder="请选择跳转方式"  style="width:300px;">
            <el-option label="redirect" value="redirect"></el-option>
            <el-option label="navigate" value="navigate"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="addBanner">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {uploadFile} from 'api/file.js'
import {getAllSwiper,deleteSwiper,addSwiper,updateSwiper} from 'api/banner.js'
import to from 'await-to-js'
export default {
  data(){
    return {
      openType:'add',           //控制弹出框的标题：add对应添加；update对应修改
      loading:true,
      list:[],
      fileList:[],              //文件上传的图片列表
      dialogFormVisible:false,  //控制弹出框隐藏和显示
      formLabelWidth:'120px',   //弹出框表单标题宽度
      form:{                    //和表单标签进行双向绑定的对象
        _id:'',                 
        goods_id:'',
        image_src:'',
        navigator_url:'',
        open_type:''
      },
      rules:{                   //编写表单的验证规则
        goods_id:{required:true,message:'请输入商品编号'},
        image_src:{required:true,message:'请选择文件'},
        navigator_url:{required:true,message:'请输入链接'},
        open_type:{required:true,message:'请选择跳转方式'}
      }
    }
  },
  methods:{
    async uploadPhoto(file){
      //文件上传
      console.log(file);
      let formData = new FormData();
      formData.append('myFile',file)
      let [error,res] = await to(uploadFile(formData))
      if(res){
        //将上传成功返回的图片地址存到form对象中
        this.form.image_src = 'http://124.221.198.104:4000/' + res.url;
      }else{
        this.$message.error(error)
      }
      return Promise.reject()
    },
    closeDialog(){
      this.$refs['myform'].resetFields();
      this.dialogFormVisible = false;
      this.fileList=[];
      this.form = {                    
        _id:'',                 
        goods_id:'',
        image_src:'',
        navigator_url:'',
        open_type:''
      }
    },
    addBanner(){
      this.$refs.myform.validate(async (valid)=>{
        if(valid){
          //验证通过
          var result=[];
          if(this.form._id.length>0){
            result = await to(updateSwiper(this.form))
          }else{
            delete this.form._id;
            result = await to(addSwiper(this.form))
          }
          let [error,res] = result;
          if(res){
            this.$message.success(res.message || res.msg)
            this.closeDialog();
            this.find();
          }else{
            this.$message.error(error)
          }
        }else{
          //验证失败
            this.$message.error("请正确填写内容")
        }
      })
    },
    open(type,obj){
      this.openType = type;
      this.dialogFormVisible = true;
      if(obj){
        this.form = obj;
        this.fileList.push({name:obj.goods_id,url:obj.image_src});
      }
    },
    del(_id){
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let [error,res] = await to(deleteSwiper(_id))
          if(res){
            this.$message({
              type: 'success',
              message: res.message
            });
            this.find();
          }else{
            this.$message({
              type: 'error',
              message: error
            });
          }
        }).catch(() => {
        });
    },
    async find(){
      let [error,res] = await to(getAllSwiper())
      if(res){
        this.list = res.message;
      }else{
        this.$message.error(error);
      }
      this.loading = false;
    }
  },
  mounted(){
    this.find();
  }
}
</script>

<style>

</style>